/******************************************************
// Copyright 2008 Derrick Pallas. All rights reserved.
//
// This file is part of c-ptr.
//
// c-ptr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// c-ptr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with c-ptr.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef LOCKED_PTR_H
#define LOCKED_PTR_H

#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>

#include "basic_ptr.h"

namespace ptr
{
  template < typename, class > class locking;
  template < typename T, class M = boost::mutex >
    class locked : public ptr::basic< T, boost::shared_ptr<T> >
                 , private boost::noncopyable
    {
    private:
      locked( );

    public:
      typedef T my_type;
      typedef boost::shared_ptr<my_type> ptr_type;
      typedef ptr::basic<my_type, ptr_type> base;
      typedef M mutex_type;

      mutex_type & mutex;
      
    protected:
      locked( const ptr_type & p, mutex_type & m )
        : base(p), mutex(m)
        { if (this->ptr) mutex.lock(); }

    public:
     ~locked( ) { if (this->ptr) mutex.unlock(); }
      locked( const locked & that );

      locking<my_type,mutex_type>
      unlock( )
      {
        locking<my_type,mutex_type>
          _( static_cast< boost::shared_ptr<my_type> >(this->ptr), mutex );
        if (this->ptr) mutex.unlock();
        this->ptr.reset();
        return _;
      }

      friend class locking<my_type,mutex_type>;
    };
}

#endif // LOCKED_PTR_H
